package com.sline.day03._03_smis.template.handler;

import com.sline.day03._03_smis.template.ResultSetHandler;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;

public class BeanHandler<T> implements ResultSetHandler {

    private Class<T> classType;
    public BeanHandler(Class<T> classType) {
        this.classType = classType;
    }

    @Override
    public T handle(ResultSet resultSet) {
        try {
            if (resultSet.next()) {
                T obj = this.classType.newInstance();

                BeanInfo beanInfo = Introspector.getBeanInfo(classType, Object.class);
                PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

                for (PropertyDescriptor pd: pds) {
                    String name = pd.getName();

                    Object value = resultSet.getObject(name);

                    pd.getWriteMethod().invoke(obj, value);
                }

                return obj;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
